package com.jian.mall.ware.service.impl;

import com.jian.mall.common.content.PurchaseDetailStatusEnum;
import com.jian.mall.common.content.PurchaseStatusEnum;
import com.jian.mall.ware.entity.PurchaseDetailEntity;
import com.jian.mall.ware.service.PurchaseDetailService;
import com.jian.mall.ware.service.WareSkuService;
import com.jian.mall.ware.vo.MergeVo;
import com.jian.mall.ware.vo.PurchaseDoneVo;
import com.jian.mall.ware.vo.PurchaseItemVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jian.mall.common.utils.PageUtils;
import com.jian.mall.common.utils.Query;

import com.jian.mall.ware.dao.PurchaseDao;
import com.jian.mall.ware.entity.PurchaseEntity;
import com.jian.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("assignee_name", key);
            });
        }
        String status = (String) params.get("status");
        if (StringUtils.isNotEmpty(status)) {
            wrapper.eq("status", status);
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();

        wrapper.eq("status", PurchaseStatusEnum.STATUS_CREATED.getCode()).or()
                .eq("status", PurchaseStatusEnum.STATUS_ASSIGNED.getCode());

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Date date = new Date();
        if (mergeVo.getPurchaseId() == null) {
            PurchaseEntity entity = new PurchaseEntity();
            entity.setCreateTime(date);
            entity.setUpdateTime(date);
            entity.setStatus(PurchaseStatusEnum.STATUS_CREATED.getCode());
            save(entity);
            mergeVo.setPurchaseId(entity.getId());
        }

        List<Long> items = mergeVo.getItems();

        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(items);

        List<PurchaseDetailEntity> list = purchaseDetailEntities.stream().filter(f ->
                        Objects.equals(f.getStatus(), PurchaseDetailStatusEnum.STATUS_CREATED.getCode()) || Objects.equals(f.getStatus(), PurchaseDetailStatusEnum.STATUS_ASSIGNED.getCode()))
                .peek(p -> {
                    p.setPurchaseId(mergeVo.getPurchaseId());
                    p.setStatus(PurchaseDetailStatusEnum.STATUS_ASSIGNED.getCode());
                }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(list);
        PurchaseEntity entity = new PurchaseEntity();
        entity.setUpdateTime(date);
        entity.setId(mergeVo.getPurchaseId());
        baseMapper.updateById(entity);
    }

    @Transactional
    @Override
    public void received(List<Long> ids) {
        Date date = new Date();

        List<PurchaseEntity> entityList = purchaseService.listByIds(ids);
        List<PurchaseEntity> list = entityList.stream()
                .filter(i ->
                        Objects.equals(i.getStatus(), PurchaseStatusEnum.STATUS_CREATED.getCode()) ||
                                Objects.equals(i.getStatus(), PurchaseStatusEnum.STATUS_ASSIGNED.getCode()))
                .peek(m -> {
                    m.setUpdateTime(date);
                    m.setStatus(PurchaseStatusEnum.STATUS_RECEIVED.getCode());
                }).collect(Collectors.toList());
        if (list.size() == 0) return;

        purchaseService.updateBatchById(list);

        purchaseDetailService.receivedPurchaseIds(list);

    }

    @Transactional
    @Override
    public void finish(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(PurchaseStatusEnum.STATUS_FINISHED.getCode());

        List<PurchaseItemVo> items = purchaseDoneVo.getItems();

        List<PurchaseDetailEntity> list = items.stream().map(m -> {
            PurchaseDetailEntity entity = new PurchaseDetailEntity();
            entity.setId(m.getItemId());
            entity.setStatus(m.getStatus());
            if (Objects.equals(m.getStatus(), PurchaseDetailStatusEnum.STATUS_ERROR.getCode())) {
                purchaseEntity.setStatus(PurchaseStatusEnum.STATUS_ERROR.getCode());
            } else {
                PurchaseDetailEntity detail = purchaseDetailService.getById(m.getItemId());
                wareSkuService.addStock(detail);
            }
            return entity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(list);
        purchaseEntity.setUpdateTime(new Date());
        purchaseService.updateById(purchaseEntity);
    }

}